package services

import (
	"GOPAAS/internal/app/model"
	"GOPAAS/internal/utils"
	"database/sql"
	"fmt"
	"strconv"
	"strings"
)

type CmsCategoryService struct {
	model.CmsCategory
}

func GetCmsCategoryService(uid int64) *CmsCategoryService {
	var CmsCategory model.CmsCategory
	if uid > 0 {
		db.First(&CmsCategory, uid)
	}
	return &CmsCategoryService{CmsCategory}
}

func (c *CmsCategoryService) GetCmsCategoryInfo() {

}

// RemoveCategories 批量删除分类
func RemoveCategories(category_id_arr []int64) error {
	db = getDB()
	var Category model.CmsCategory
	res := db.Delete(&Category, category_id_arr)
	return res.Error
}

// AddCmsCategory 添加分类
func AddCmsCategory(name string, parent_id int64, login_user_id int64) error {
	db = getDB()
	var Category model.CmsCategory
	var parent sql.NullInt64
	if parent_id > 0 {
		parent.Valid = true
		parent.Int64 = parent_id
	}
	Category = model.CmsCategory{
		Name:     name,
		ParentId: parent,
		ResCommon: model.ResCommon{
			CreateUid: login_user_id,
			WriteUid:  login_user_id,
		},
	}
	tx := db.Begin()
	result := tx.Select("Name", "ParentId", "active", "public", "create_uid", "write_uid").Create(&Category)
	if result.Error != nil {
		return result.Error
	}
	var code string
	var new_id = Category.Id
	if new_id < 999 {
		code = fmt.Sprintf("N%03d", Category.Id)
	} else {
		code = "N" + strconv.Itoa(int(Category.Id))
	}
	var tmp_path_name_arr = []string{name}
	var tmp_path_id_arr = []int64{Category.Id}
	for {
		if parent_id == 0 {
			break
		}
		var cate model.CmsCategory
		db.First(&cate, parent_id)
		parent_id = cate.ParentId.Int64
		tmp_path_id_arr = append(tmp_path_id_arr, cate.Id)
		tmp_path_name_arr = append(tmp_path_name_arr, cate.Name)
	}
	var path_id_arr = make([]int64, len(tmp_path_id_arr), len(tmp_path_id_arr))
	var path_name_arr = make([]string, len(tmp_path_name_arr), len(tmp_path_name_arr))
	for k, v := range tmp_path_id_arr {
		path_id_arr[len(tmp_path_id_arr)-k-1] = v
	}
	for k, v := range tmp_path_name_arr {
		path_name_arr[len(tmp_path_name_arr)-k-1] = v
	}
	path_id_str := strings.Join(utils.Int64ToStringSlice(path_id_arr), "/")
	path_name_str := strings.Join(path_name_arr, "/")
	result = tx.Model(model.CmsCategory{}).Where("id", new_id).Updates(map[string]interface{}{
		"code":          code,
		"complete_name": path_name_str,
		"parent_path":   path_id_str + "/",
	})
	if result.Error != nil {
		tx.Rollback()
		return result.Error
	}
	tx.Commit()
	return nil
}

// EditCmsCategory 修改分类
func (c *CmsCategoryService) EditCmsCategory(name string, login_user_id int64) error {
	db = getDB()
	c.Name = name
	c.WriteUid = login_user_id
	result := db.Save(c.CmsCategory)
	return result.Error
}

// GetNewsCategory 获取新闻分类
func GetNewsCategory(lang string) (res []Area) {
	db = getDB()
	var categ []int64
	db.Model(&model.CmsNews{}).Where("lang=? and state=?", lang, "已发布").Pluck("categ_id", &categ)
	db.Model(&model.CmsCategory{}).Where("id in ? and parent_path like ?", categ, "1/%").Distinct().Find(&res)
	return
}
